package com.tjhk.netty.mapping;

import com.tjhk.netty.mapping.annotation.HandlerMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.Map;

/**
 * 利用springcontext自动加载
 */
public class SpringHandlerMappingRegister extends AbstractHandlerMapperRegister implements ApplicationContextAware {

    private final static Logger log = LoggerFactory.getLogger(SpringHandlerMappingRegister.class);

    /** 匹配HandlerMapper的注解value */
    private String name = "";

    public SpringHandlerMappingRegister() {
    }

    public SpringHandlerMappingRegister(String name) {
        this.name = name;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("HandlerMapping[name={}]开始初始化加载....",this.name==""?"default":this.name);
        Map<String, Object> objectMap = applicationContext.getBeansWithAnnotation(HandlerMapper.class);
        int count=0;
        for (Map.Entry<String, Object> entry : objectMap.entrySet()) {
            Object object = entry.getValue();
            HandlerMapper riskRuleType = object.getClass().getAnnotation(HandlerMapper.class);
            String name = riskRuleType.name();
            if (name.equals(this.name)){
                super.registerHandlers(object);
                count++;
            }
        }
        if (count > 1)
            log.warn("有两个相同命名[name={}]的HandlerMapping，若Mapping方法命名相同会造成处理异常！",this.name);
        if (count == 0)
            log.warn("未找到[name={}]的HandlerMapping，请查看注册Name是否与HandlerMapping注解一致！",this.name);
        log.info("HandlerMappingHandlerMapping[name={}]初始化加载完成",this.name==""?"default":this.name);
    }
}